package com.wenc.psi.fgmt.homefgmt;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wenc.psi.R;
import com.wenc.psi.databinding.FragmentPartBinding;
import com.wenc.psi.pojo.Part;
import com.wenc.psi.rvAdapter.PartAdapter;
import com.wenc.psi.vmd.PartViewModel;
import com.wenc.psi.vmd.SaleViewModel;

public class PartFragment extends Fragment {

    private SaleViewModel saleViewModel;
    private PartAdapter partAdapter;
    private PartViewModel partViewModel;
    private FragmentPartBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_part, container, false);
        // Inflate the layout for this fragment
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        saleViewModel = new ViewModelProvider(getActivity()).get(SaleViewModel.class);
        partAdapter = new PartAdapter();
        // 设置recyclerView布局
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        // 设置适配器
        binding.recyclerView.setAdapter(partAdapter);
        // 获取ViewModel
        partViewModel = new ViewModelProvider(getActivity()).get(PartViewModel.class);
        // 对ViewModel的数据进行监听
        partViewModel.getPartLive().observe(getActivity(), parts -> {
            partAdapter.setPartList(parts);
            partAdapter.notifyDataSetChanged();
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        // 点击添加事件
        partAdapter.setOnItemClickListener(new PartAdapter.OnItemClickListener() {
            @Override
            public void onItemChoiceClick(Part part) {
                System.out.println("添加：" + part.getName());
                saleViewModel.addPart(part);
            }
        });
        // 点击关闭事件
        binding.btClose.setOnClickListener(v -> {
            getActivity().getSupportFragmentManager().beginTransaction().hide(this).commit();
        });
        // 点击完成事件
        binding.btFinish.setOnClickListener(v -> {
            getActivity().getSupportFragmentManager().beginTransaction().hide(this).commit();
        });
    }
}